/**
 * Dear programmer:
 * When I wrote this code, only god and I knew how it worked.
 * Now, only god knows it!
 *
 * @author: Pegasus  Date: 2019-02-20 Time: 23:33
 */

import React, {Component} from 'react';
import {connect} from 'react-redux';
import {NavigationActions, StackActions} from 'react-navigation';
import LoadingView from "../../../component/LoadingView/LoadingView"
import User from "../../../model/User/User"
import {doSetCache, doSetToken, doSetUserSession} from "./Action"
import {JPushClear} from "../../../util/JPush/JPushUtil"
import global from "../../../configuration/global";
import {getWs,creWebSocket} from "../../../configuration/global";

class AuthScreen extends Component {

  componentDidMount(): void {
    let {dispatch} = this.props;

    JPushClear();

    User.getUser(user => {
      if (user&&user.token) {

        dispatch(doSetToken(user.token));

        dispatch(doSetUserSession(user.userid, user.dep, user.hotelId));

        User.getCache(cache => {
          if (cache && cache.cache) {
            dispatch(doSetCache(cache.cache));

            let action;

            let qms_role_arr = user.qms_role.split(',')

            if(qms_role_arr.indexOf("TEST")>=0){ //测试页面
                this.props.navigation.navigate('AlertNavigator',{transition:'forInitial'});
            }else if(qms_role_arr.indexOf("ADMIN")>=0){ //客房员工
                // this.props.navigation.navigate('MainNavigator');
                this.props.navigation.navigate('Homepage_repair',{transition:'forInitial'});
            }else{
                this.props.navigation.navigate('HousekeeperMainNavigator');
            }

            let resetAction = StackActions.reset({
              index: 0,
              actions: action
            })

            //推送
            if(getWs()==null){
                creWebSocket(global.hotelId,user.userid)
            }

            this.props.navigation.dispatch(resetAction)

          } else {
            let resetAction = StackActions.reset({
              index: 0,
              actions: [
                NavigationActions.navigate({routeName: 'LoginScreen'})
              ]
            })
            this.props.navigation.dispatch(resetAction)
          }
        })

      } else {
        let resetAction = StackActions.reset({
          index: 0,
          actions: [
            NavigationActions.navigate({routeName: 'LoginScreen'})
          ]
        })
        this.props.navigation.dispatch(resetAction)
      }
    })
  }

  render() {
    return (
      <LoadingView/>
    )
  }
}

const props = state => {
  return {}
}

export default AuthScreen = connect(props)(AuthScreen);
